import { EnhancedPlugins } from './enhanced-index';
import { PluginTestRunner } from './test-runner';
import { Logger } from '../logger';

/**
 * 插件测试示例
 */
export class PluginTestExamples {
  /**
   * 创建测试用的书源插件代码
   */
  static createTestBookSourcePlugin(): string {
    return `
plugin.exports = class TestBookSource {
  static ID = 'test-booksource-plugin-001';
  static TYPE = plugin.type.BOOK_SOURCE;
  static GROUP = '测试';
  static NAME = '测试书源';
  static VERSION = '1.0.0';
  static VERSION_CODE = 1;
  static PLUGIN_FILE_URL = 'https://example.com/test.js';
  static BASE_URL = 'https://example.com';

  constructor({ request, store, cheerio, nanoid, uuid }) {
    this.request = request;
    this.store = store;
    this.cheerio = cheerio;
    this.nanoid = nanoid;
    this.uuid = uuid;
  }

  async search(searchkey) {
    console.log('搜索关键词:', searchkey);
    
    // 模拟搜索结果
    return [
      {
        name: '测试小说1',
        author: '测试作者1',
        detailPageUrl: 'https://example.com/book/1',
        latestChapterName: '第一章',
        cover: 'https://example.com/cover1.jpg'
      },
      {
        name: '测试小说2',
        author: '测试作者2',
        detailPageUrl: 'https://example.com/book/2',
        latestChapterName: '第二章',
        cover: 'https://example.com/cover2.jpg'
      }
    ];
  }

  async getDetail(detailPageUrl) {
    console.log('获取详情页:', detailPageUrl);
    
    // 模拟详情页数据
    return {
      name: '测试小说详情',
      author: '测试作者',
      cover: 'https://example.com/cover.jpg',
      description: '这是一个测试小说的描述',
      status: '连载中',
      category: '玄幻',
      wordCount: '100万字',
      updateTime: new Date().toISOString(),
      chapters: [
        {
          name: '第一章 开始',
          url: 'https://example.com/chapter/1'
        },
        {
          name: '第二章 继续',
          url: 'https://example.com/chapter/2'
        }
      ]
    };
  }

  async getTextContent(chapter) {
    console.log('获取章节内容:', chapter.name);
    
    // 模拟章节内容
    return [
      '这是第一段内容。',
      '这是第二段内容。',
      '这是第三段内容。',
      '章节内容结束。'
    ];
  }
};
`;
  }

  /**
   * 创建测试用的书城插件代码
   */
  static createTestBookStorePlugin(): string {
    return `
plugin.exports = class TestBookStore {
  static ID = 'test-bookstore-plugin-001';
  static TYPE = plugin.type.BOOK_STORE;
  static GROUP = '测试';
  static NAME = '测试书城';
  static VERSION = '1.0.0';
  static VERSION_CODE = 1;
  static PLUGIN_FILE_URL = 'https://example.com/test-store.js';
  static BASE_URL = 'https://example.com';

  constructor({ request, store, cheerio, nanoid, uuid }) {
    this.request = request;
    this.store = store;
    this.cheerio = cheerio;
    this.nanoid = nanoid;
    this.uuid = uuid;
  }

  get config() {
    return {
      热门推荐: this.getHotBooks.bind(this),
      新书上架: this.getNewBooks.bind(this),
      完本精品: this.getFinishedBooks.bind(this)
    };
  }

  async getHotBooks() {
    console.log('获取热门推荐');
    return [
      {
        name: '热门小说1',
        author: '热门作者1',
        detailPageUrl: 'https://example.com/hot/1',
        cover: 'https://example.com/hot1.jpg',
        description: '热门小说描述1'
      },
      {
        name: '热门小说2',
        author: '热门作者2',
        detailPageUrl: 'https://example.com/hot/2',
        cover: 'https://example.com/hot2.jpg',
        description: '热门小说描述2'
      }
    ];
  }

  async getNewBooks() {
    console.log('获取新书上架');
    return [
      {
        name: '新书1',
        author: '新作者1',
        detailPageUrl: 'https://example.com/new/1',
        cover: 'https://example.com/new1.jpg',
        description: '新书描述1'
      }
    ];
  }

  async getFinishedBooks() {
    console.log('获取完本精品');
    return [
      {
        name: '完本小说1',
        author: '完本作者1',
        detailPageUrl: 'https://example.com/finished/1',
        cover: 'https://example.com/finished1.jpg',
        description: '完本小说描述1'
      }
    ];
  }
};
`;
  }

  /**
   * 创建测试用的TTS插件代码
   */
  static createTestTTSPlugin(): string {
    return `
plugin.exports = class TestTTSEngine {
  static ID = 'test-tts-engine-plugin-001';
  static TYPE = plugin.type.TTS_ENGINE;
  static GROUP = '测试';
  static NAME = '测试TTS引擎';
  static VERSION = '1.0.0';
  static VERSION_CODE = 1;
  static PLUGIN_FILE_URL = 'https://example.com/test-tts.js';

  constructor({ request, store, cheerio, nanoid, uuid }) {
    this.request = request;
    this.store = store;
    this.cheerio = cheerio;
    this.nanoid = nanoid;
    this.uuid = uuid;
  }

  async getVoiceList() {
    console.log('获取语音列表');
    return [
      { name: '测试女声', value: 'test-female' },
      { name: '测试男声', value: 'test-male' },
      { name: '测试童声', value: 'test-child' }
    ];
  }

  async transform(texts, options, next, end) {
    console.log('开始文本转语音', { texts: texts.length, options });
    
    try {
      for (let i = 0; i < texts.length; i++) {
        if (options.signal?.aborted) {
          throw new Error('Aborted');
        }

        // 模拟音频生成
        const audioData = new Uint8Array(1024); // 模拟音频数据
        const blob = new Blob([audioData], { type: 'audio/wav' });
        
        // 模拟异步处理
        await new Promise(resolve => setTimeout(resolve, 100));
        
        next({ blob, index: i }, i);
      }
      
      end();
    } catch (error) {
      console.error('TTS转换错误:', error);
      throw error;
    }
  }
};
`;
  }

  /**
   * 运行完整的插件系统测试
   */
  static async runCompleteTest(): Promise<void> {
    try {
      Logger.info('开始插件系统完整测试');

      // 创建增强版插件管理器
      const plugins = new EnhancedPlugins();
      const testRunner = new PluginTestRunner(plugins);

      // 测试书源插件
      Logger.info('测试书源插件...');
      const bookSourceCode = this.createTestBookSourcePlugin();
      const bookSourceInstance = await plugins.importEnhanced(null, bookSourceCode, {
        enable: true,
        debug: true,
        force: true,
      });

      // 测试书城插件
      Logger.info('测试书城插件...');
      const bookStoreCode = this.createTestBookStorePlugin();
      const bookStoreInstance = await plugins.importEnhanced(null, bookStoreCode, {
        enable: true,
        debug: true,
        force: true,
      });

      // 测试TTS插件
      Logger.info('测试TTS插件...');
      const ttsCode = this.createTestTTSPlugin();
      const ttsInstance = await plugins.importEnhanced(null, ttsCode, {
        enable: true,
        debug: true,
        force: true,
      });

      // 运行功能测试
      Logger.info('运行书源功能测试...');
      await plugins.testPlugin('test-booksource-plugin-001', {
        searchKeyword: '测试',
        detailUrl: 'https://example.com/book/1',
        chapter: {
          name: '第一章',
          url: 'https://example.com/chapter/1',
        },
      });

      Logger.info('运行书城功能测试...');
      await plugins.testPlugin('test-bookstore-plugin-001');

      Logger.info('运行TTS功能测试...');
      await plugins.testPlugin('test-tts-engine-plugin-001');

      // 运行所有测试
      Logger.info('运行完整测试套件...');
      const allTestResults = await testRunner.runAllTests();

      // 生成测试报告
      const report = testRunner.generateTestReport();
      Logger.info('测试报告:\n' + report);

      // 获取性能报告
      const performanceReport = plugins.getPluginPerformanceReport();
      Logger.info('性能报告:', performanceReport);

      Logger.info('插件系统完整测试完成');

      return {
        testResults: allTestResults,
        performanceReport,
        report,
      };

    } catch (error) {
      Logger.error('插件系统测试失败:', error);
      throw error;
    }
  }

  /**
   * 运行性能压力测试
   */
  static async runPerformanceTest(): Promise<void> {
    Logger.info('开始性能压力测试');

    const plugins = new EnhancedPlugins();
    
    // 导入测试插件
    const bookSourceCode = this.createTestBookSourcePlugin();
    await plugins.importEnhanced(null, bookSourceCode, {
      enable: true,
      debug: false,
      force: true,
    });

    const plugin = plugins.getPluginById('test-booksource-plugin-001');
    if (!plugin?.instance) {
      throw new Error('插件未正确加载');
    }

    // 执行大量搜索操作
    const searchPromises = [];
    for (let i = 0; i < 100; i++) {
      searchPromises.push(
        (plugin.instance as any).search(`测试关键词${i}`),
      );
    }

    const startTime = Date.now();
    await Promise.all(searchPromises);
    const endTime = Date.now();

    Logger.info(`性能测试完成: 100次搜索耗时 ${endTime - startTime}ms`);

    // 获取性能统计
    const stats = plugins.getPluginPerformanceReport('test-booksource-plugin-001');
    Logger.info('性能统计:', stats);
  }
}